export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

export function getDay(day) {
  var today = new Date()
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
  today.setTime(targetday_milliseconds) // 注意，这行是关键代码
  var tYear = today.getFullYear()
  var tMonth = today.getMonth()
  var tDate = today.getDate()
  tMonth = doHandleMonth(tMonth + 1)
  tDate = doHandleMonth(tDate)
  return tYear + '-' + tMonth + '-' + tDate
}

function doHandleMonth(month) {
  var m = month
  if (month.toString().length == 1) {
    m = '0' + month
  }
  return m
}

// 获取两日期之间日期列表函数
export function getdiffdate(stime, etime) {
  // 初始化日期列表，数组
  var diffdate = new Array()
  var i = 0
  // 开始日期小于等于结束日期,并循环
  while (stime <= etime) {
    diffdate[i] = stime

    // 获取开始日期时间戳
    var stime_ts = new Date(stime).getTime()
    // console.log('当前日期：'+stime   +'当前时间戳：'+stime_ts);

    // 增加一天时间戳后的日期
    var next_date = stime_ts + (24 * 60 * 60 * 1000)

    // 拼接年月日，这里的月份会返回（0-11），所以要+1
    var next_dates_y = new Date(next_date).getFullYear() + '-'
    var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-'
    var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate()

    stime = next_dates_y + next_dates_m + next_dates_d
    // 增加数组key
    i++
  }
  return diffdate
}

export function getMonth(num) {
  const data = new Date()
  const nowYear = data.getFullYear()
  const nowMonth = data.getMonth() + 1
  let year = nowYear; let month = nowMonth - num
  if (month < 1) {
    year--
    month = month + 12
  }
  month = doHandleMonth(month)
  return year + '-' + month
}
// 获取月份
export function getMonthList(start, end) {
  const startArr = start.split('-')
  const endArr = end.split('-')
  let year1 = parseInt(startArr[0])
  let month1 = parseInt(startArr[1])
  const year2 = parseInt(endArr[0])
  const month2 = parseInt(endArr[1])
  const num = (year2 - year1) * 12 + (month2 - month1)
  const arry = new Array()
  for (var i = 0; i <= num; i++) {
    if (month1 > 12) {
      year1 = year1 + 1
      month1 = month1 - 12
    }
    let month = month1
    if (month < 10) {
      month = '0' + month
    }
    arry[i] = year1 + '-' + month
    month1++
  }
  return arry
}

